package cn.dengta.webapp.user.module.file;

import lombok.Getter;
import lombok.Setter;
import me.codeplayer.util.*;

/**
 * 对接云存储服务所需的配置参数实体
 */
@Setter
@Getter
public class RemoteConfig {

	public static final String PLACEHOLDER_BUCKET_NAME = "<bucketName>";
	public static final String PLACEHOLDER_REGION = "<region>";
	public static final String PLACEHOLDER_END_POINT = "<endPoint>";
	//
	/** 访问key ID */
	protected String accessKeyId;
	/** 访问key 密钥 */
	protected String accessKeySecret;
	/** 访问的区域节点 */
	protected String region;
	/** 访问操作的 bucket 名称 */
	protected String bucketName;
	/** 上传的远程目标路径 */
	protected String endPoint;
	/** 用于对外访问的URL前缀 */
	protected String accessPoint;
	//
	protected transient String endPointSource;
	protected transient String accessPointSource;

	public RemoteConfig init(String accessKeyId, String accessKeySecret, String region, String endPoint, String bucketName, String accessPoint) {
		this.accessKeyId = accessKeyId;
		this.accessKeySecret = accessKeySecret;
		this.bucketName = bucketName;
		this.region = region;
		this.endPoint = endPoint;
		this.accessPoint = accessPoint;
		return this;
	}

	public String getAccessURL(String fileName) {
		return accessPoint + '/' + fileName;
	}

	protected void initEndPoint() {
		endPointSource = endPoint;
		endPoint = parsePathParams(endPointSource);
	}

	protected void initAccessPoint() {
		accessPointSource = accessPoint;
		if (StringUtil.isEmpty(accessPoint)) {
			accessPoint = endPoint;
		} else {
			accessPoint = parsePathParams(accessPointSource);
		}
		if (!accessPoint.endsWith("/")) {
			accessPoint += '/';
		}
	}

	public String parsePathParams(String source) {
		return source.replace(PLACEHOLDER_BUCKET_NAME, X.expectNotNull(bucketName, ""))
				.replace(PLACEHOLDER_REGION, X.expectNotNull(region, ""))
				.replace(PLACEHOLDER_END_POINT, X.expectNotNull(endPoint, ""));
	}

	public String initConfig() {
		if (StringUtil.isEmpty(accessKeyId)) {
			return "accessKeyId must be not empty.";
		}
		if (StringUtil.isEmpty(accessKeySecret)) {
			return "accessKeySecret must be not empty.";
		}
		if (StringUtil.isEmpty(bucketName)) {
			return "bucketName must be not empty.";
		}
		if (StringUtil.isEmpty(region)) {
			return "region at least one must be not empty.";
		}
		if (StringUtil.isEmpty(endPoint)) {
			return "endPoint at least one must be not empty.";
		}
		initEndPoint();
		initAccessPoint();
		return null;
	}

	public void init() {
		String error = initConfig();
		Assert.isNull(error, error);
	}

}
